﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Se.Framework.Common.Data
{
    public abstract class BusinessLayerBase<T> : IBusinessLayer<T>
        where T : class
    {
        private readonly Lazy<IMapper> mapper = ObjectRegistry.Current.ResolveLazy<IMapper>();

        protected virtual IMapper Mapper
        {
            get
            {
                return mapper.Value;
            }
        }

        protected virtual IRepository<T> Repository
        {
            get
            {
                return ObjectRegistry.Current.Resolve<IRepository<T>>();
            }
        }

        public virtual IQueryable<T> GetItems()
        {
            return Repository.Query();
        }

        public virtual T Find(int id)
        {
            return Repository.Find(id);
        }

        public virtual void AddItem(T item)
        {
            Repository.Add(item);
        }

        public virtual void UpdateItem(T item)
        {
            Repository.Update(item);
        }

        public virtual void DeleteItem(T item)
        {
            Repository.Delete(item);
        }

        public virtual IEnumerable<TDto> GetDtoItems<TDto>()
        {
            return GetItems().ToList()
                .Select(e => Mapper.Map<TDto>(e)).ToList();
        }

        public virtual TDto FindDto<TDto>(int id)
        {
            return Mapper.Map<TDto>(Repository.Find(id));
        }
    }
}
